/**
 * 深克隆json
 * @param {T} json
 * @return {T}
 */
export const deepCloneJSON = json => JSON.parse(JSON.stringify(json));

/**
 * 拆解query字符串
 * @param {string} text
 */
export const parseQuery = text => {
  if (!text) {
    return {};
  }
  try {
    const query = {};
    const queryString =
      String(text)[0] == '?' ? String(text).substr(1) : String(text);
    queryString.split('&').forEach(item => {
      const [key, value] = item.split('=');
      query[key] = value;
    });
    return query;
  } catch (err) {
    return {};
  }
};

/**
 * 将对象转为query
 * @param {Object} query
 */
export const stringifyQuery = query => {
  try {
    return Object.keys(query)
      .filter(key => query[key] !== undefined && query[key] !== null)
      .map(key => `${key}=${query[key]}`)
      .join('&');
  } catch (err) {
    return '';
  }
};

/**
 * 组装货宝宝图片src地址
 * @param {String} href 货宝宝baseUrl中域名参数
 * @param {String} path 图片地址名
 * @param {Object} options 配置
 * @return {String}
 */
export const getImgUrl = (
  href,
  path = '',
  { width = '', height = '' } = {}
) => {
  let imgUrl = '';
  const [originPath] = path.split('@');
  if (!originPath.startsWith('http')) {
    // if(href.indexOf("cdn-hbbsystem.hbbyun.com")<0){
    //   href = href.replace(/http:/g, location.protocol);
    // }
    imgUrl = `${href}/${originPath}`;
  } else {
    imgUrl = originPath;
  }

  if (width || height) {
    const query = `${width && `_${width}w`}${height && `_${height}h`}${width &&
      height &&
      `_1e_1c`}`;
    imgUrl = `${imgUrl}@${query}`;
    if (/(png)$/i.test(originPath)) {
      imgUrl = `${imgUrl}.png`;
    } else if (/(gif)$/i.test(originPath)) {
      imgUrl = `${imgUrl}.gif`;
    }
  }
  return imgUrl;
};

/**
 * 函数防抖
 * @param {Function} func
 * @param {Number} wait
 */
export const debounce = (func, wait = 200) => {
  let timer;
  return function(...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      timer = null;
      func.apply(this, args);
    }, wait);
  };
};

/**
 * 函数节流
 * @param {Function} func 包装方法
 * @param {Number} wait 节流间隔
 */
export const throttle = (func, wait) => {
  let timer;
  let previous = 0;
  return function(...args) {
    const now = +new Date();
    // remaining 不触发下一次函数的剩余时间
    const remaining = wait - (now - previous);
    if (remaining < 0) {
      if (timer) {
        clearTimeout(timer);
        timer = null;
      }
      previous = now;
      func.apply(this, args);
    } else if (!timer) {
      timer = setTimeout(() => {
        previous = +new Date();
        timer = null;
        func.apply(this, args);
      }, remaining);
    }
  };
};

/**
 * 获取随机数位的随机数
 */
export const getRandomCode = digit =>
  `${new Array(digit).fill('0').join('')}${Math.floor(
    Math.random() * 10 ** digit
  )}`.substr(-digit);

/**
 * 创建本地单据号（日期+随机数）
 */
export const createLocalSheetID = () => {
  const today = new Date();
  const year = today.getFullYear();
  const month = `0${today.getMonth() + 1}`.substr(-2);
  const date = `0${today.getDate()}`.substr(-2);
  const hour = `0${today.getHours()}`.substr(-2);
  const minute = `0${today.getMinutes()}`.substr(-2);
  const second = `0${today.getSeconds()}`.substr(-2);
  const millisecond = `00${today.getMilliseconds()}`.substr(-3);
  const randomNum = getRandomCode(6);
  return `${year}${month}${date}${hour}${minute}${second}${millisecond}${randomNum}`;
};

/**
 * 反转字符串
 * @param {String} string 字符串
 */
export const stringReverse = string =>
  String(string)
    .split('')
    .reverse()
    .join('');

/**
 * 将数组切分成chunk
 * @param {Array} array
 * @param {number} chunk
 */
export const chunk = (array, chunk = 1) =>
  chunk >= 1
    ? new Array(Math.ceil(array.length / chunk))
        .fill(null)
        .map((_, index) => array.slice(index * chunk, (index + 1) * chunk))
    : [];

/**
 * 将rpx转为px
 * @param {Number} rpx
 */
export const rpx2px = rpx => {
  const { windowWidth } = uni.getSystemInfoSync();
  return (windowWidth / 750) * rpx;
};

/**
 * 将px转为rpx
 * @param {Number} px
 */
export const px2rpx = px => {
  const { windowWidth } = uni.getSystemInfoSync();
  return (750 / windowWidth) * px;
};

/**
 * 验证字符串是否符合数据库合法
 * @param {String} str 待验证字符串
 */
export const checkIsValidateString = str =>
  /^[a-zA-Z0-9\u4e00-\u9fa5\(\)\（\）\-\_]+$/.test(str);

